/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.loja.view.component.composition;

import static br.com.loja.util.converter.ViewParser.getNumberOf;

import br.com.loja.view.component.factory.ViewHadler;
import javax.swing.JTextField;

/**
 *
 * @author DavidLuiz
 */
public class CommonToOne<T> extends JTextField implements ViewHadler<T> {

    private final Class<T> clazz;

    public CommonToOne(Class<T> clazz) {
        this.clazz = clazz;
        setColumns(25);
    }

    @Override
    public void setValueModel(T value) {

        String text = "";

        if (value != null) {
            text = value.toString();
        }

        setText(text);
    }

    @Override
    public T getValueModel() {

        String value = getText() != null ? getText() : "0";

        if (isString()) {
            return (T) value;
        }

        if (isNumber()) {
            return getNumber(value);
        }

        return null;

    }

    private T getNumber(String value) {
        return (T) getNumberOf(value, (Class<? extends Number>) clazz);
    }

    private boolean isNumber() {
        return Number.class.isAssignableFrom(clazz);
    }

    private boolean isString() {
        return String.class.isAssignableFrom(clazz);
    }

}
